<template>
<div>
 <el-card>
   <el-alert
       title="添加商品信息"
       type="info"
       center
       :closable="false"
       show-icon>
   </el-alert>
   <el-steps :space="200" :active="activeIndex-0" align-center finish-status="success">
     <el-step title="基本信息"></el-step>
     <el-step title="商品参数"></el-step>
     <el-step title="商品属性"></el-step>
     <el-step title="商品图片"></el-step>
     <el-step title="商品内容"></el-step>
     <el-step title="完成"></el-step>
   </el-steps>

   <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-position="top">
   <el-tabs v-model="activeIndex" tab-position="left" :before-leave="beforTabLeave" @tab-click="tabClicked">
     <el-tab-pane label="基本信息" name="0">
       <el-form-item label="商品名称" prop="goods_name">
         <el-input v-model="addForm.goods_name"></el-input>
       </el-form-item>
       <el-form-item label="商品价格" prop="goods_price">
         <el-input v-model="addForm.goods_price" type="number"></el-input>
       </el-form-item>
       <el-form-item label="商品重量" prop="goods_weight">
         <el-input v-model="addForm.goods_weight" type="number"></el-input>
       </el-form-item>
       <el-form-item label="商品数量" prop="goods_number">
         <el-input v-model="addForm.goods_number" type="number"></el-input>
       </el-form-item>

       <el-form-item label="商品分类" prop="goods_cat">
         <el-cascader
             clearable
             v-model="addForm.goods_cat"
             :options="cateList"
             :props="cascaderProps"
             @change="parentCateChange" popper-class="CateCascader" class="CateCascader"></el-cascader>

       </el-form-item>
     </el-tab-pane>
     <el-tab-pane label="商品参数" name="1">
       <el-form-item :label="item.attr_name" v-for="(item, index) in manyTableData" :key="item.arrt_id">
         <el-checkbox-group v-model="item.attr_vals">
         <el-checkbox border :label="item2" v-for="(item2, index2) in item.attr_vals" :key="index2"></el-checkbox>
       </el-checkbox-group>
       </el-form-item>
     </el-tab-pane>
     <el-tab-pane label="商品属性" name="2">
       <el-form-item v-for="(item, index) in onlyTableData" :key="item.attr_id" :label="item.attr_name">
         <el-input v-model="item.attr_vals"></el-input>
       </el-form-item>
     </el-tab-pane>
     <el-tab-pane label="商品图片" name="3">

       <el-upload :action="uploadUrl"
           :on-preview="handlePreview"
           :on-remove="handleRemove"
           :headers="headerObj"
           :on-success="handleSuccess"
           list-type="picture">
         <el-button size="small" type="primary">点击上传</el-button>

       </el-upload>


     </el-tab-pane>
     <el-tab-pane label="商品内容" name="4">
       <quill-editor v-model="addForm.goods_introduce"></quill-editor>
       <el-button type="primary" class="addBtn" @click="add">添加商品</el-button>
     </el-tab-pane>
   </el-tabs>
   </el-form>

 </el-card>

  <el-dialog title="图片预览" :visible.sync="previewVisible" width="50%">
      <img class="preview" :src="previewPath" alt="图片预览">
  </el-dialog>
</div>
</template>

<script>
export default {
  name: "addGoods",
  data(){
    return{
      activeIndex:'0',
      addForm:{
        goods_name:'',
        goods_price:1,
        goods_weight:1,
        goods_number:1,
        goods_cat:[],
        pics:[],
        goods_introduce:'',
        attrs:[]
      },
      addFormRules: {
        goods_name:[{
          required: true, message: '请输入商品名称', trigger: 'blur'
        }],
        goods_price:[{
          required: true, message: '请输入商品价格', trigger: 'blur'
        }],
        goods_weight:[{
          required: true, message: '请输入商品重量', trigger: 'blur'
        }],
        goods_number:[{
          required: true, message: '请输入商品数量', trigger: 'blur'
        }],
        goods_cat:[{
          required: true, message: '请输入商品分类', trigger: 'blur'
        }],
      },
      cateList:[],
      cascaderProps:{
        expandTrigger: 'hover',
        value:'cat_id',
        label:'cat_name',
        children:'children',
      },
      manyTableData:[],
      onlyTableData:[],
      // 上传图片地址
      uploadUrl:'https://lianghj.top:8888/api/private/v1/upload',
      // 上传图片请求头
      headerObj:{
        Authorization : window.sessionStorage.getItem('token')
      },
    //  上传图片预览路径
      previewPath:'',
      previewVisible:false,

    //  富文本

    }
  },
  created() {
    this.getCateList()
  },
  methods:{
    async getCateList(){
      const {data:res} = await this.$http.get('categories')
      // console.log(res);
      if (res.meta.status !== 200) return this.$Message.error("失败")
      this.cateList = res.data

    },
    //级联选择器
    async parentCateChange(){
      console.log(this.addForm.goods_cat);

      const {data:res} = await this.$http.get(`categories/${this.getCateID}/attributes`,{
        params:{sel:'many'}
      })
      // console.log(res);
      if (res.meta.status !== 200) return this.$Message.error("失败")

      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(','):[]

      })
      this.manyTableData = res.data

      const {data:res2} = await this.$http.get(`categories/${this.getCateID}/attributes`,{
        params:{sel:'only'}
      })
      // console.log(res);
      if (res2.meta.status !== 200) return this.$Message.error("失败")

      this.onlyTableData = res2.data


    },
    //tabs切换
    beforTabLeave(activeName, oldActiveName){
      if (oldActiveName === '0' && this.addForm.goods_cat.length === 0){
        this.$Message.error("请选择分类")
        return false
      }
    },
    async tabClicked(){
      // if (this.activeIndex === '1'){
      //   const {data:res} = await this.$http.get(`categories/${this.getCateID}/attributes`,{
      //     params:{sel:'many'}
      //   })
      //   // console.log(res);
      //   if (res.meta.status !== 200) return this.$Message.error("失败")
      //
      //   res.data.forEach(item => {
      //     item.attr_vals = item.attr_vals ? item.attr_vals.split(','):[]
      //
      //   })
      //   this.manyTableData = res.data
      // }
      //
      // if (this.activeIndex === '2'){
      //   const {data:res} = await this.$http.get(`categories/${this.getCateID}/attributes`,{
      //     params:{sel:'only'}
      //   })
      //   // console.log(res);
      //   if (res.meta.status !== 200) return this.$Message.error("失败")
      //
      //   this.onlyTableData = res.data
      // }
      },
    //图片预览效果
    handlePreview(file){
      // console.log(file)
      this.previewPath = file.response.data.url
      this.previewVisible = true
    },
    //图片删除
    handleRemove(file){
       const filePath = file.response.data.tmp_path
      // console.log(filePath)
      const index = this.addForm.pics.findIndex(item => item.pic === filePath)
      // console.log(index)
      this.addForm.pics.splice(index,1)
    },
    //添加图片成功
    handleSuccess(response){
      const pics = {pic:response.data.tmp_path}

      this.addForm.pics.push(pics)
    },
    add(){
      this.$refs.addFormRef.validate(async valid =>{
        if (!valid){
          return  this.$Message.error("请输入正确的表单项目")
        }
        // console.log("操作")
      const newAddForm = JSON.parse(JSON.stringify(this.addForm))
        newAddForm.goods_cat = newAddForm.goods_cat.join(',')
        this.manyTableData.forEach(item => {
          const newInfo ={
            attr_id:item.attr_id,
            attr_value:item.attr_vals.join(',')
          }
          newAddForm.attrs.push(newInfo)
        })
        this.onlyTableData.forEach(item => {
          const newInfo ={
            attr_id:item.attr_id,
            attr_value:item.attr_vals
          }
          newAddForm.attrs.push(newInfo)
        })
        // console.log(newAddForm)

        const {data:res} = await this.$http.post('goods',newAddForm)
        // console.log(res);
        if (res.meta.status !== 201) return this.$Message.error(res.meta.msg)

        this.$Message.success(res.meta.msg)

        this.$router.push('/goods')
      })
    }

  },
  computed:{
    getCateID(){
      return this.addForm.goods_cat[this.addForm.goods_cat.length-1]
    }
  }
}
</script>

<style>
.el-checkbox{
  margin: 0 15px 0 0 !important;
}

.preview{
  width: 100%;
}
.ql-editor {     min-height: 300px; }
.addBtn{
  margin-top: 15px;
}
</style>